import { PopupExposed, SelectPropsType } from '@/types'
import { Ref, onMounted, onUnmounted, reactive, watch } from 'vue'

interface StateType {
    focusedIndex: number
    popShown: boolean
}

export function useSelect(props: SelectPropsType, popupRef: Ref<PopupExposed | undefined>, items: Ref<any[]>) {
    const state = reactive<StateType>({
        focusedIndex: -1,
        popShown: false,
    })

    watch(() => state.popShown, () => {
        state.focusedIndex = -1
    })

    onMounted(() => {
        methods.addEventListener()
    })

    onUnmounted(() => {
        methods.removeEventListener()
    })

    const methods = {
        addEventListener() {
            window.document.addEventListener('keydown', methods.onDocumentKeydown)
        },
        removeEventListener() {
            window.document.removeEventListener('keydown', methods.onDocumentKeydown)
        },
        onDocumentKeydown(e: KeyboardEvent) {
            if (!state.popShown) {
                return
            }
            if (e.keyCode === 38) {
                let children = methods.getPopEl().children
                let focusedIndex = state.focusedIndex
                for (let i = focusedIndex - 1; i >= 0; i--) {
                    if (!props.getDisabledFunc!(items.value![i])) {
                        (children[i] as HTMLElement).focus()
                        state.focusedIndex = i
                        break
                    }
                }
            }
            else if (e.keyCode === 40) {
                let children = methods.getPopEl().children
                let focusedIndex = state.focusedIndex
                for (let i = focusedIndex + 1; i < children.length; i++) {
                    if (!props.getDisabledFunc!(items.value![i])) {
                        (children[i] as HTMLElement).focus()
                        state.focusedIndex = i
                        break
                    }
                }
            }
        },
        getPopEl() {
            return popupRef.value!.getPopEl()
        },
    }
}